﻿using MySql.Data.MySqlClient;
using System;

namespace MySQL
{
    class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine("Hello World!");
			Mysql mysql = new Mysql();
			mysql.OpenSql();


			Console.WriteLine("点击登录账号 123 密码 123");
			Console.ReadKey();
			mysql.Login("231y3721", "123");
			Console.WriteLine("点击插入数据账号 777 密码 777");
			mysql.Logon("777", "777");
			Console.ReadKey();
			mysql.CloseSql();
		}

	}
	class Mysql
	{
		private MySqlConnection mysql = new MySqlConnection();


		private string host = "127.0.0.1";                //数据库IP地址

		private string port = "3306";                     //端口号

		private string username = "root";                 //数据库账号

		private string password = "NTK123123";       //数据库密码

		private string basename = "chenjian";             //数据库名

		private string tablename = "login";            //使用的表名
		/// <summary>
		/// 打开数据库
		/// </summary>
		public void OpenSql()
		{
			try
			{
				//连接数据库
				string mySqlString = string.Format("Database={0};Data Source={1};User Id={2};Password={3};port={4};charset=utf8", basename, host, username, password, port);
				mysql = new MySqlConnection(mySqlString);
				mysql.Open();
				Console.WriteLine("数据库连接成功");
			}
			catch (MySqlException e)
			{
				Console.WriteLine(e.Message);
			}
		}



		/// <summary>
		/// 关闭数据库
		/// </summary>
		public void CloseSql()
		{
			if (mysql != null)
			{
				mysql.Close();
				mysql.Dispose();
				mysql = null;
			}
		}
		/// <summary>
		/// 登录
		/// </summary>
		public void Login(string name, string pass)
		{
			string sql = "SELECT* FROM `login` WHERE id =1";
			MySqlCommand comd = new MySqlCommand(sql, mysql);
			MySqlDataReader reader = comd.ExecuteReader();
			if (reader.HasRows)
			{
				Console.WriteLine("登录成功");
				reader.Close();
			}
			else
			{

				reader.Close();
			}

		}
		public void Logon(string a, string b)
		{
			string str = "insert into `login`(account,password) values ('777','777') ";
			try
			{
				MySqlCommand LogonComd = new MySqlCommand(str, mysql);
				if (LogonComd.ExecuteNonQuery() == 1)
				{
					Console.WriteLine("注册成功");
				}
				else
				{
					Console.WriteLine("注册失败");
				}
			}
			catch (MySqlException e)
			{
				Console.WriteLine("注册出错" + e.Message);
			}
		}
	}
}

